const { SERVER_HOST, SERVER_PORT } = require("../config/server");
const { singleUpdate } = require("../service/file.service");
const { UPLOAD_PATH } = require("../config/path");
const path = require("path");

class FileController {
  async singleFileUpdate(ctx, next) {
    // 1.获取上传图片对应的信息
    console.log(ctx.request.file);
    // console.log(ctx.request.files);

    // const { id } = ctx.userInfo;
    const { filename, mimetype, size } = ctx.request.file;

    // 当前路径“__dirname” 和 路径 进行拼接

    // const fileURL = `${SERVER_HOST}:${SERVER_PORT}/${}/avatar/${id}`;
    /*
      path.resolve(`${SERVER_HOST}:${SERVER_PORT}`,UPLOAD_PATH,filename);
      > path.resolve会返回一个操作系统相关的绝对路径，而不是 URL
        结果为H:\AnimalProtection\animal-protection-Server\http:\localhost:8000\uploads\1699671914525_GodGodK.webp
      > path.join 方法来处理相对路径的拼接
        UPLOAD_PATH的值是uploads，而filename的值是example.jpg，那么path.join('.', UPLOAD_PATH, filename)
        将会返回./uploads/example.jpg，其中./ 表示当前目录。
      >
        const folderUrl = UPLOAD_PATH.slice(2);
        const folderUrl = UPLOAD_PATH.split("./")[1];
        const fileURL = `${SERVER_HOST}:${SERVER_PORT}/${folderUrl}/${filename}`;
        其实不用将图片的文件夹路径上传上去，因为已经将那个文件夹设置成静态资源服务器，
        直接通过文件夹中的文件名就能请求到数据
    */

    console.log(ctx.uploadPath);
    //将第一个总的路径 切割掉，因为已经配置了静态服务器
    // UPLOAD_PATH 该目录下的文件可以当成静态资源进行访问
    const uploadPath = ctx.uploadPath.split(UPLOAD_PATH)[1];
    console.log(uploadPath);

    const fileURL = `${SERVER_HOST}:${SERVER_PORT}${uploadPath}/${filename}`;
    ctx.body = {
      code: 200,
      message: "单文件上传成功~",
      data: fileURL,
    };
  }

  async fileArrayUpdate(ctx, next) {
    // console.log(ctx.request.files);

    const uploadPath = ctx.uploadPath.split(UPLOAD_PATH)[1];

    // const { id } = ctx.userInfo;
    // const { filename, mimetype, size } = ctx.request.files;
    // for of遍历数组的每一项
    const fileURLArray = [];
    for (const fileItem of ctx.request.files) {
      // console.log("fileItem", fileItem);
      const fileItemURL = `${SERVER_HOST}:${SERVER_PORT}${uploadPath}/${fileItem.filename}`;
      fileURLArray.push(fileItemURL);
    }

    ctx.body = {
      code: 200,
      message: "多文件上传成功~",
      data: fileURLArray,
    };
  }
}

module.exports = new FileController();
